package com.nineclock.sign.service.impl;
import java.util.Date;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.DateTimeUtil;
import com.nineclock.sign.dto.*;
import com.nineclock.sign.excel.SignCustomHandler;
import com.nineclock.sign.excel.SignExcelMember;
import com.nineclock.sign.listener.SignExcelMemberListener;
import com.nineclock.sign.mapper.SignInfoMapper;
import com.nineclock.sign.mapper.SignPictureMapper;
import com.nineclock.sign.pojo.SignInfo;
import com.nineclock.sign.pojo.SignPicture;
import com.nineclock.sign.service.SignService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
public class SignServiceImpl implements SignService {
    @Autowired
    private SignInfoMapper signInfoMapper;
    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private SignPictureMapper pictureMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * APP: 获取当前用户当天签到次数
     * Tag ：王炳涛
     * 接口路径：GET/sign/getDayCount
     */
    @Override
    public Integer getDayCount() {
        //查询当前用户所属企业的员工id
        Long companyUserId = CurrentUserHolder.get().getCompanyUserId();

        if (companyUserId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取当天日期
        String nowDate = LocalDate.now().toString();

//        从redis中查询用户当天签到次数
        String dayCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + nowDate;
        System.out.println("dayCountKey = " + dayCountKey);
        String dayCount = redisTemplate.opsForValue().get(dayCountKey);

       if ( dayCount== null){
            dayCount = String.valueOf(0);
            //throw new NcException(ResponseEnum.USER_NOT_FOUND);    // 该用户当天还未打卡
        }
    /*    if (StringUtils.isEmpty(dayCount)){
            //如果缓存当中没有数据  就从数据库中查询
            LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SignInfo::getCompanyUserId, companyUserId);//
            wrapper.eq(SignInfo::getCreateDate, nowDate);
            List<SignInfo> signInfoList = signInfoMapper.selectList(wrapper);
            int signCount = signInfoList.size();
            if ( signCount== 0){
                throw new NcException(ResponseEnum.USER_NOT_FOUND);    // 该用户当天还未打卡
            }
            return signCount;
        }*/

        return Integer.parseInt(dayCount);

    }


    /**
     * PC: 查询签到列表
     * Tag ：王子
     * 接口路径：GET/sign/sign
     */
    @Override
    public PageResult<SignDepDTO> sign(Long page, Long pageSize, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取时间
        List<String> spanDateList = DateTimeUtil.getSpanDateList(startTime, endTime);
        //查询在此期间签过到的用户id集合
        IPage<SignInfo> iPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignInfo::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.between(SignInfo::getCreateDate, startTime, endTime);
        wrapper.select(SignInfo::getCompanyUserId);
        wrapper.groupBy(SignInfo::getCompanyUserId);
        iPage = signInfoMapper.selectPage(iPage, wrapper);
        List<SignInfo> records = iPage.getRecords();
        List<Long> idList = new ArrayList<>();
        for (SignInfo record : records) {
            idList.add(record.getCompanyUserId());
        }
        //根据idList获取用户基本信息
        List<SysCompanyUserDTO> companyUserDTOList = companyUserFeign.getCompanyUserByIdList(idList, CurrentUserHolder.get().getCompanyId()).getData();
        //根据用户基本信息,dateList返回signDepDTOList
        List<SignDepDTO> signDepDTOList = this.getSignDepDTOList(companyUserDTOList, spanDateList);
        return new PageResult<>(iPage.getTotal(), iPage.getPages(), signDepDTOList);
    }

    /**
     * PC: 导出签到列表
     * Tag ：王子
     * 接口路径：GET/sign/export
     */
    @Override
    public void export(String startTime, String endTime) throws IOException {
        //获取时间
        List<String> spanDateList = DateTimeUtil.getSpanDateList(startTime, endTime);
        List<Long> idList = signInfoMapper.findCompanyUserIdByDate(startTime, endTime,CurrentUserHolder.get().getCompanyId());
        List<SysCompanyUserDTO> companyUserDTOList = companyUserFeign.getCompanyUserByIdList(idList, CurrentUserHolder.get().getCompanyId()).getData();
        List<SignDepDTO> signDepDTOList = this.getSignDepDTOList(companyUserDTOList, spanDateList);


        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setHeader("Content-disposition", "attachment;filename=Sign.xls");
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setCharacterEncoding("utf-8");

        // 生成excel文件，下载
        EasyExcel.write(response.getOutputStream())
                .excelType(ExcelTypeEnum.XLS)
                .registerWriteHandler(this.horizontalCellStyleStrategy())
                .registerWriteHandler(new SignCustomHandler())
                .sheet("考勤报表")
                .head(this.handleHeaders(signDepDTOList))
                .doWrite(this.handleData(signDepDTOList));

    }
    /**
     * 签到报表发邮件
     * @param companyId
     * @return
     */
    @Override
    public String generatePunchReport(Long companyId) {
        // 获取本月第一天和最后一天
        String startTime = DateTimeUtil.getCurrentMonthFirstDay();
        String endTime = DateTimeUtil.getCurrentMonthLastDay();
        //获取时间
        List<String> spanDateList = DateTimeUtil.getSpanDateList(startTime, endTime);
        List<Long> idList = signInfoMapper.findCompanyUserIdByDate(startTime, endTime, companyId);
        List<SysCompanyUserDTO> companyUserDTOList = companyUserFeign.getCompanyUserByIdList(idList, companyId).getData();
        List<SignDepDTO> signDepDTOList = this.getSignDepDTOList(companyUserDTOList, spanDateList);

        // 指定文件路径，D:\签到数据\公司id
        String folder = "D:" + File.separator + "签到数据" +  File.separator + companyId;
        File file = new File(folder);

        if(!file.exists()){
            // 如果文件夹不存在，创建文件夹
            file.mkdirs();
        }

        // D:\签到数据\公司id\公司名称-2021-11-签到数据.xls
        String fileName = folder + File.separator + companyUserDTOList.get(0).getCompanyName()
                + "-" + startTime.substring(0, 7) + "-签到数据.xls";

        EasyExcel.write(new File(fileName))
                .excelType(ExcelTypeEnum.XLS)
                .registerWriteHandler(this.horizontalCellStyleStrategy())
                .registerWriteHandler(new SignCustomHandler())
                .sheet("签到报表")
                .head(this.handleHeaders(signDepDTOList))
                .doWrite(this.handleData(signDepDTOList));

        return fileName;
    }


    /**
     * 根据用户基本信息,dateList返回signDepDTOList
     * Tag : 王子
     *
     * @param companyUserDTOList
     * @param spanDateList
     * @return
     */
    public List<SignDepDTO> getSignDepDTOList(List<SysCompanyUserDTO> companyUserDTOList, List<String> spanDateList) {
        List<SignDepDTO> signDepDTOList = companyUserDTOList.stream().map(companyUserDTO -> {
            SignDepDTO signDepDTO = new SignDepDTO();
            signDepDTO.setId(Integer.parseInt(companyUserDTO.getId().toString()));
            signDepDTO.setPost(companyUserDTO.getPost());

            signDepDTO.setUsername(companyUserDTO.getUserName());
            signDepDTO.setWorkNumber(companyUserDTO.getWorkNumber());

            DepartmentDTO departmentDTO = new DepartmentDTO();
            departmentDTO.setId(Integer.parseInt(companyUserDTO.getDepartmentId().toString()));
            departmentDTO.setName(companyUserDTO.getDepartmentName());

            signDepDTO.setDepartment(departmentDTO);


            LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SignInfo::getCompanyUserId, companyUserDTO.getId());
            List<SignInfo> signInfoList = signInfoMapper.selectList(wrapper);
            // 将打卡记录进行分组，按照日期分组，key为每一天的日期，value为签到记录
            Map<String, List<SignInfo>> signInfoMap = signInfoList.stream().collect(Collectors.groupingBy(SignInfo::getCreateDate));

            signDepDTO.setSigns(spanDateList.stream().map(date -> {
                SignDTO signDTO = new SignDTO();
                if (!CollectionUtils.isEmpty(signInfoMap.get(date))) {

                    signDTO.setSignCount(signInfoMap.get(date).size());
                    signDTO.setSignDate(date);

                } else {
                    signDTO.setSignCount(0);
                    signDTO.setSignDate(date);
                }
                return signDTO;
            }).collect(Collectors.toList()));
            return signDepDTO;

        }).collect(Collectors.toList());
        return signDepDTOList;
    }

    /**
     * 设置样式
     * Tag : 王子
     */
    public HorizontalCellStyleStrategy horizontalCellStyleStrategy() {

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //内容策略 - 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //设置字体
        WriteFont font = new WriteFont();
        font.setFontName("阿里巴巴普惠体");
        font.setFontHeightInPoints((short) 11);
        contentWriteCellStyle.setWriteFont(font);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(contentWriteCellStyle, contentWriteCellStyle);

        return horizontalCellStyleStrategy;
    }

    /**
     * 动态构造每一行数据
     * Tag : 王子
     *
     * @param signDepDTOList
     * @return
     */
    private List<List<String>> handleData(List<SignDepDTO> signDepDTOList) {
        List<List<String>> dataList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(signDepDTOList)) {
            //遍历每一行数据
            for (SignDepDTO signDepDTO : signDepDTOList) {
                List<String> row = new ArrayList<>();
                row.add(signDepDTO.getUsername());
                row.add(signDepDTO.getId().toString());
                row.add(signDepDTO.getDepartment().getName());
                row.add(signDepDTO.getPost());
                List<SignDTO> signs = signDepDTO.getSigns();
                if (!CollectionUtils.isEmpty(signs)) {
                    for (SignDTO sign : signs) {
                        row.add(sign.getSignCount().toString());
                    }
                }
                dataList.add(row);
            }

        }
        return dataList;
    }

    /**
     * 动态构造表头
     * Tag : 王子
     *
     * @param signDepDTOList
     * @return
     */
    private List<List<String>> handleHeaders(List<SignDepDTO> signDepDTOList) {
        List<List<String>> headers = new ArrayList<>();

        headers.add(Arrays.asList("姓名"));
        headers.add(Arrays.asList("工号"));
        headers.add(Arrays.asList("部门"));
        headers.add(Arrays.asList("职位"));

        if (!CollectionUtils.isEmpty(signDepDTOList)) {
            SignDepDTO signDepDTO = signDepDTOList.get(0);// 取出第一条数据

            List<SignDTO> signs = signDepDTO.getSigns();

            if (!CollectionUtils.isEmpty(signs)) {
                for (SignDTO sign : signs) {
                    headers.add(Arrays.asList(sign.getSignDate()));
                }
            }

        }
        return headers;
    }

    /**
     * APP：签到
     * 杨定康
     *
     * @param signUserDTO
     * @throws FileNotFoundException
     */
    @Override
    public void sign(SignUserDTO signUserDTO) throws FileNotFoundException {
        //1.参数校验
        if (signUserDTO == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //2 封装签到信息
        SignInfo signInfo = BeanHelper.copyProperties(signUserDTO, SignInfo.class);
        //2.1 设置签到基本信息：员工id，公司id，创建时间
        signInfo.setCompanyUserId(CurrentUserHolder.get().getCompanyUserId());
        signInfo.setCompanyId(CurrentUserHolder.get().getCompanyId());
        signInfo.setCreateTime(new Date());

        // 2.2 设置签到日期和月份（以服务端为准，否则用户可以在客户端修改手机时间打卡）
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = simpleDateFormat.format(new Date());
        signInfo.setCreateDate(dateString);
        //设置签到年月份，使用Calendar类（月份是0-11）
        Calendar instance = Calendar.getInstance();
        int y = instance.get(Calendar.YEAR);
        int m = instance.get(Calendar.MONTH) + 1;
        String year = String.valueOf(y);
        String month = String.valueOf(m);
        //拼接年份+月份字符串
        String createMonth = year + "-" + month;
        signInfo.setCreateMonth(createMonth);

        //2.3 设置签到经度、纬度和地址
        signInfo.setLat(signUserDTO.getLat());
        signInfo.setLng(signUserDTO.getLng());
        signInfo.setAddress(signUserDTO.getAddress());

        //2.4 设置签到备注、拜访对象和手机标识
        signInfo.setRemark(signUserDTO.getRemark());
        signInfo.setVisit(signUserDTO.getVisit());
        signInfo.setImei(signUserDTO.getImei());

        //2.5保存签到信息到sign_info表

        signInfoMapper.insert(signInfo);

        //2.6 把签到的图片阿里云地址保存到签到图片表中
        //2.6.1 设置sign_picture表的签到id
        SignPicture signPicture = new SignPicture();
        signPicture.setSignId(signInfo.getId());

        String[] imageList = signUserDTO.getImages().split(",");
        for (String image : imageList) {
            signPicture.setUrl(image);
            pictureMapper.insert(signPicture);
        }

        // 3.更新用户当天签到次数和当月签到次数到redis

        // 更新用户当天签到次数到redis
        Integer dayCount;
//        TODO redis
        //设置redis当日签到次数的key
        String dayCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + signInfo.getCreateDate();
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(dayCountKey))) {
            dayCount = 0;
        } else {
            String dayCountStr = redisTemplate.opsForValue().get(dayCountKey);
            dayCount = Integer.parseInt(dayCountStr);
        }
        //每签到一次，redis当日签到次数+1
        dayCount++;
        //把int类型dayCount转为String类型
        String redisDayCountStr = String.valueOf(dayCount);
        //更新redis当日签到次数
        redisTemplate.opsForValue().set(dayCountKey, redisDayCountStr);


        //更新用户当月签到次数到redis
        Integer monthCount;
        //设置redis当月签到次数的key
        String monthCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + signInfo.getCreateMonth();
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(monthCountKey))) {
            monthCount = 0;
        } else {
            String monthCountStr = redisTemplate.opsForValue().get(monthCountKey);
            monthCount = Integer.valueOf(monthCountStr);
        }
        //每签到一次，redis当月签到次数+1
        monthCount++;
        //把int类型dayCount转为String类型
        String redismonthCountStr = String.valueOf(monthCount);

        redisTemplate.opsForValue().set(monthCountKey, redismonthCountStr);

    }

    /**
     * APP: 查询本月签到记录
     * Tag ：王炳涛
     * 接口路径：GET/sign/pagingSignCurrentUserByMonth
     */
    @Override
    public List<SignUserDTO> pagingSignCurrentUserByMonth(String dateStr) {
        //判断传入的参数是否为空
        if (dateStr == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //查询当前用户所属企业的员工id
        Long companyUserId = CurrentUserHolder.get().getCompanyUserId();
        LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignInfo::getCreateMonth, dateStr);  //传入的月份和数据库查询的月份
        wrapper.eq(SignInfo::getCompanyUserId, companyUserId);//
        List<SignInfo> signInfoList = signInfoMapper.selectList(wrapper);//获取签到集合列表

        ArrayList<SignUserDTO> signUserDTOArrayList = new ArrayList<>(); //创建SignUserDTO集合用于存入数据


        for (SignInfo signInfo : signInfoList) {
            String username = CurrentUserHolder.get().getUsername();  //获取员工用户名
            SignUserDTO signUserDTO = new SignUserDTO();
            signUserDTO.setId(0L);
            signUserDTO.setCompanyId(signInfo.getCompanyId()); //公司ID
            signUserDTO.setCompanyUserId(signInfo.getCompanyUserId()); //公司员工id


            Date createTime = signInfo.getCreateTime();
            System.out.println("createTime = " + createTime);
            String dateToStr = DateTimeUtil.dateToStr(createTime);

            System.out.println("dateToStr = " + dateToStr);
            signUserDTO.setCreateTime(dateToStr);  //签到时间

            signUserDTO.setCreateDate(signInfo.getCreateDate()); //签到日期
            signUserDTO.setCreateMonth(signInfo.getCreateMonth()); //签到月份
            signUserDTO.setLat(new BigDecimal(signInfo.getLat().doubleValue())); //经度
            signUserDTO.setLng(new BigDecimal(signInfo.getLng().doubleValue())); //纬度
            signUserDTO.setAddress(signInfo.getAddress()); // 签到地址
            signUserDTO.setRemark(signInfo.getRemark()); // 签到备注
            signUserDTO.setVisit(signInfo.getVisit());  //拜访对象
            signUserDTO.setImei(signInfo.getImei()); // 手机标示
            Integer dayCount = getDayCount();// 获取当日签到次数
            signUserDTO.setDayCount(dayCount.toString());  // 当日签到次数


            LambdaQueryWrapper<SignPicture> wrapper1 = new LambdaQueryWrapper();
            wrapper1.eq(SignPicture::getSignId, signInfo.getId());
            List<SignPicture> pictureList = pictureMapper.selectList(wrapper1);


            StringBuilder urlList = new StringBuilder();
            ArrayList<String> signPictureUrlList = new ArrayList<>();
            for (SignPicture signPicture : pictureList) {
                String url = signPicture.getUrl();
                signPictureUrlList.add(url);//                添加到图片列表集合
                urlList = urlList.append(url).append(",");// 拼接图片地址字符串
            }
            System.out.println("urlList = " + urlList);
            signUserDTO.setImages(urlList.toString());   // 图片列表字符串
            int size = signInfoList.size();  // 当月签到次数
            String monthCount = size + "";
            signUserDTO.setMonthCount(monthCount);  // 当月签到次数
            signUserDTO.setSignPictureUrlList(signPictureUrlList); // 签到图片列表
            signUserDTO.setUserName(username);
            //添加到集合
            signUserDTOArrayList.add(signUserDTO);
        }
//        根据日期进行排序
        Collections.sort(signUserDTOArrayList, (o1, o2) -> {
            String createTime1 = o1.getCreateTime();
            String createTime2 = o2.getCreateTime();
            return createTime2.compareTo(createTime1);
        });
        return signUserDTOArrayList;
    }
    /**
     * PC-直接导入员工签到数据
     * Tag : 王子
     * 接口路径：POST/sign/uploadExcel
     */
    @Override
    public void importData(MultipartFile excelFile) throws IOException {
        // 健壮性判断
        if (excelFile == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Long companyId = CurrentUserHolder.get().getCompanyId();
        // 解析数据
        EasyExcel.read(excelFile.getInputStream(), SignExcelMember.class,
                new SignExcelMemberListener(this,companyId)).sheet(0).doRead();
    }
    /**
     * PC-处理导入excel数据
     * Tag : 王子
     * 接口路径：POST/sign/uploadExcel
     */
    @Override
    public void handleParsedData(List<SignExcelMember> memberList,Long companyId) {
        List<SignInfo> signInfoList = memberList.stream().map(signExcelMember -> {
            SysCompanyUserDTO companyUser = this.getCompanyUserByWorkNumber(signExcelMember.getWorkNumber(),companyId);
            SignInfo signInfo = new SignInfo();
            signInfo.setCompanyId(companyUser.getCompanyId());
            signInfo.setCompanyUserId(companyUser.getId());
            signInfo.setCreateTime(DateTimeUtil.strToDate(signExcelMember.getCreateTime()));
            signInfo.setCreateDate(DateTimeUtil.dateToStr(signInfo.getCreateTime(), DateTimeUtil.TIME_FORMAT_2));
            signInfo.setCreateMonth(DateTimeUtil.dateToStr(signInfo.getCreateTime(), DateTimeUtil.TIME_FORMAT_4));
            signInfo.setAddress(signExcelMember.getAddress());
            signInfo.setRemark(signExcelMember.getRemark());
            signInfo.setVisit(signExcelMember.getVisit());
            signInfo.setImei("PC导入");
            if (this.pendingSignTime(signInfo)) {
                return signInfo;
            }
            return null;
        }).collect(Collectors.toList());

        this.saveSignInfo(signInfoList);
    }

    /**
     * 持久化导入数据
     * @param signInfoList
     */
    private void saveSignInfo(List<SignInfo> signInfoList) {
        for (SignInfo signInfo : signInfoList) {
            signInfoMapper.insert(signInfo);
        }
    }

    /**
     * 判定手机号、邮箱是否已经被注册、工号是否已存在
     * @param signInfo
     */
    private boolean pendingSignTime(SignInfo signInfo) {
        LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignInfo::getCreateTime,signInfo.getCreateTime());
        wrapper.eq(SignInfo::getCompanyId,signInfo.getCompanyId());
        wrapper.eq(SignInfo::getCompanyUserId,signInfo.getCompanyUserId());
        List<SignInfo> signInfoList = signInfoMapper.selectList(wrapper);
        return CollectionUtils.isEmpty(signInfoList);
    }

    public SysCompanyUserDTO getCompanyUserByWorkNumber(String workNumber,Long companyId){
        SysCompanyUserDTO companyUserDTO = companyUserFeign.getCompanyUserByWorkNumber(workNumber, companyId).getData();
        return companyUserDTO;
    }

    @Override
    public List<SignUserListDTO> listSignAllUser(String dateStr) {
        //获取当前企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //得到所有企业员工集合
        List<SysCompanyUserDTO> companyUserDTOList = companyUserFeign.queryAllCompanyUser().getData();

        //每个员工的签到数据集合
        List<SignUserListDTO> signUserListDTOList = new ArrayList<>();

        //遍历每个企业员工
        companyUserDTOList.forEach(companyUserDTO -> {
            //每条签到数据集合
            List<SignUserDTO> signUserDTOList = new ArrayList<>();
            //一个员工的签到数据集合
            SignUserListDTO signUserListDTO = new SignUserListDTO();
            LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SignInfo::getCompanyId, companyId);
            wrapper.eq(SignInfo::getCreateDate, dateStr);
            wrapper.eq(SignInfo::getCompanyUserId, companyUserDTO.getId());

            //得到每个用户当天的签到列表
            List<SignInfo> signInfoList = signInfoMapper.selectList(wrapper);
            if (CollectionUtils.isEmpty(signInfoList)) {
                return;
            }

            //遍历每一个用户的签到列表
            signInfoList.forEach(signInfo -> {
                //查询图片列表集合
                LambdaQueryWrapper<SignPicture> pictureWrapper = new LambdaQueryWrapper<>();
                pictureWrapper.eq(SignPicture::getSignId, signInfo.getId());
                List<SignPicture> signPictures = pictureMapper.selectList(pictureWrapper);
                //转成dto对象
                SignUserDTO signUserDTO = BeanHelper.copyProperties(signInfo, SignUserDTO.class);

                //封装数据
                String dateToStr = DateTimeUtil.dateToStr(signInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                signUserDTO.setCreateTime(dateToStr);
                signUserDTO.setUserName(companyUserDTO.getUserName());
                signUserDTO.setDayCount(String.valueOf(signInfoList.size()));//设置当天签到次数
                signUserDTO.setImages(getImages(signPictures));//图片列表字符串
                signUserDTO.setSignPictureUrlList(getSignPictureUrlList(signPictures));//签到图片列表
                signUserDTOList.add(signUserDTO);
                signUserListDTO.setSignResponseList(signUserDTOList);
                signUserListDTO.setUsername(companyUserDTO.getUserName());
            });

            signUserListDTOList.add(signUserListDTO);
        });


        return signUserListDTOList;
    }

    //获取图片列表字符串
    public String getImages(List<SignPicture> signPictures) {
        StringBuilder stringBuilder = new StringBuilder();
        signPictures.forEach(signPicture -> {
            stringBuilder.append(signPicture.getUrl() + ",");
        });
        return stringBuilder.toString();
    }

    //获取图片列表集合
    public List<String> getSignPictureUrlList(List<SignPicture> signPictures) {
        List<String> SignPictureUrlList = new ArrayList<>();
        signPictures.forEach(signPicture -> {
            SignPictureUrlList.add(signPicture.getUrl());
        });
        return SignPictureUrlList;
    }
}
